// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/
//
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is an internal header file, you should not include this.

#ifndef MUDUO_NET_SOCKET_H
#define MUDUO_NET_SOCKET_H

#include <boost/noncopyable.hpp>

namespace learnmuduo
{

class InetAddress;

///
/// Wrapper of socket file descriptor.
///
/// It closes the sockfd when desctructs.
/// It's thread safe, all operations are delagated to OS.
class Socket : boost::noncopyable // Socket 文件描述符的轻量包装类
{
 public:
  explicit Socket(int sockfd)
    : sockfd_(sockfd)
  { }

  ~Socket(); // 析构时自动关闭套接字，所有操作最终都委托给内核，线程安全由内核保障

  int fd() const { return sockfd_; } // 返回底层的文件描述符

  /// abort if address in use
  void bindAddress(const InetAddress& localaddr); // 绑定地址，失败直接终止程序
  /// abort if address in use
  void listen(); // 开始监听，失败直接终止程序

  /// On success, returns a non-negative integer that is
  /// a descriptor for the accepted socket, which has been
  /// set to non-blocking and close-on-exec. *peeraddr is assigned.
  /// On error, -1 is returned, and *peeraddr is untouched.
  int accept(InetAddress* peeraddr); // 接受新连接: 成功返回非负 fd，并将对端地址写入 peeraddr；失败返回 -1; 返回的 fd 已经设置为非阻塞和 close-on-exec

  ///
  /// Enable/disable SO_REUSEADDR
  ///
  void setReuseAddr(bool on); // TODO: ? 设置/取消 SO_REUSEADDR（地址复用），便于服务器重启

 private:
  const int sockfd_;
};

}
#endif  // MUDUO_NET_SOCKET_H
